package com.i2works.smartluolong.web.service.company.impl;

import com.alibaba.fastjson.JSONObject;
import com.i2works.smartluolong.utils.base.*;
import com.i2works.smartluolong.utils.basecommon.BaseCommonServiceImpl;
import com.i2works.smartluolong.utils.exception.DAOException;
import com.i2works.smartluolong.utils.exception.ServiceException;
import com.i2works.smartluolong.web.dal.company.dao.ICompanyChangeDAO;
import com.i2works.smartluolong.web.entity.company.*;
import com.i2works.smartluolong.web.entity.flow.FlowInfoDO;
import com.i2works.smartluolong.web.entity.flow.FlowInfoQuery;
import com.i2works.smartluolong.web.entity.flow.FlowProcessDO;
import com.i2works.smartluolong.web.service.company.*;
import com.i2works.smartluolong.web.service.flow.IFlowInfoService;
import com.i2works.smartluolong.web.service.flow.IFlowProcessService;
import com.xiaoleilu.hutool.util.CollectionUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 工商变更 - 基础信息实现类
 *
 * @author Liu Yutao <koal@vip.qq.com>
 * @date 2018/3/14 16:42
 */

@Service("companyChangeService")
public class CompanyChangeServiceImpl extends BaseCommonServiceImpl<CompanyChangeQuery, CompanyChangeDO> implements ICompanyChangeService {

    private final ICompanyChangeDAO companyChangeDAO;
    private final ICompanyApplyService companyApplyService;
    private final ICompanyApplyMemberService companyApplyMemberService;
    private final ICompanyChangeMemberService companyChangeMemberService;
    private final ICompanyApplyImagesService companyApplyImagesService;
    private final ICompanyChangeImagesService companyChangeImagesService;
    private final IFlowInfoService flowInfoService;
    private final IFlowProcessService flowProcessService;

    @Autowired
    public CompanyChangeServiceImpl(ICompanyChangeDAO companyChangeDAO, ICompanyApplyService companyApplyService, ICompanyApplyMemberService companyApplyMemberService, ICompanyChangeMemberService companyChangeMemberService, ICompanyApplyImagesService companyApplyImagesService, ICompanyChangeImagesService companyChangeImagesService, IFlowInfoService flowInfoService, IFlowProcessService flowProcessService) {
        this.companyChangeDAO = companyChangeDAO;
        this.companyApplyService = companyApplyService;
        this.companyApplyMemberService = companyApplyMemberService;
        this.companyChangeMemberService = companyChangeMemberService;
        this.companyApplyImagesService = companyApplyImagesService;
        this.companyChangeImagesService = companyChangeImagesService;
        this.flowInfoService = flowInfoService;
        this.flowProcessService = flowProcessService;
    }


    /**
     * 获取审核人员可管理的申请列表
     */
    @Override
    public List<CompanyChangeDO> queryListByAuditor(CompanyChangeQuery query) throws ServiceException {
        try {
            return companyChangeDAO.queryListByAuditor(query);
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 获取审核人员可管理的申请列表统计
     */
    @Override
    public Integer queryCountByAuditor(CompanyChangeQuery query) throws ServiceException {
        try {
            return companyChangeDAO.queryCountByAuditor(query);
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 更新变更状态
     *
     * @param companyChangeDO 申请实体
     * @param auditorId       审核人员ID
     * @param isClaim         是否认领状态
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void updateChangeStatus(CompanyChangeDO companyChangeDO, Integer auditorId, Boolean isClaim) throws ServiceException {
        try {
            //更新申请表
            companyChangeDAO.update(companyChangeDO);
            //新增流程记录
            FlowInfoQuery infoQuery = new FlowInfoQuery();
            infoQuery.setItemId(companyChangeDO.getId());
            infoQuery.setItemType(FlowItemTypeEnum.COMPANY_CHANGE.getKey());
            FlowInfoDO infoDO = flowInfoService.query(infoQuery);

            infoDO.setItemStatus(companyChangeDO.getChangeStatus());
            //如果是认领（待审核），就设置审核人ID为空(-1，mybatis自行处理)
            if (isClaim) {
                infoDO.setAuditorId(FlowConstant.base.NULL);
            } else {
                infoDO.setAuditorId(auditorId);
            }
            //如果状态是4（核准通过），设置状态为已完成，并复制变更表数据到申请表
            if (companyChangeDO.getChangeStatus().equals(CompanyStatusEnum.STATUS_4.getKey())) {
                infoDO.setComplete(FlowConstant.complete.TRUE);
                //复制数据
                if (CompanyConstant.change.CHANGE.equals(companyChangeDO.getChangeType())) {
                    //变更
                    copyChange2Apply(companyChangeDO);
                } else {
                    //备案
                    copyRecord2Apply(companyChangeDO);
                }

            }
            infoDO.setUpdateName(companyChangeDO.getUpdateName());
            infoDO.setUpdateTime(companyChangeDO.getUpdateTime());
            flowInfoService.update(infoDO);
            //插入记录表
            FlowProcessDO flowProcessDO = new FlowProcessDO();
            flowProcessDO.setAuditorId(auditorId);
            flowProcessDO.setItemId(companyChangeDO.getId());
            flowProcessDO.setItemType(FlowItemTypeEnum.COMPANY_CHANGE.getKey());
            //洛阳云舟网络科技有限公司 - 公司申请
            flowProcessDO.setItemTitle(companyChangeDO.getCompanyName() + "-" + FlowItemTypeEnum.COMPANY_CHANGE.getValue());
            flowProcessDO.setMessage(companyChangeDO.getAuditMessage());
            flowProcessDO.setAuditStatus(companyChangeDO.getChangeStatus());
            flowProcessDO.setUpdateName(companyChangeDO.getUpdateName());
            flowProcessDO.setCreateName(companyChangeDO.getUpdateName());
            flowProcessService.save(flowProcessDO);
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 复制 变更数据 ==> 基础信息表
     */
    private void copyChange2Apply(CompanyChangeDO companyChangeDO) throws ServiceException {
        //基本信息
        CompanyApplyDO companyApplyDO = new CompanyApplyDO();
        BeanUtils.copyProperties(companyChangeDO, companyApplyDO);
        companyApplyDO.setId(companyChangeDO.getApplyId());
        companyApplyService.saveOrUpdate(companyApplyDO);
        //法人信息
        CompanyChangeMemberQuery changeLegalQuery = new CompanyChangeMemberQuery();
        changeLegalQuery.setChangeId(companyChangeDO.getId());
        changeLegalQuery.setIdentity(CompanyMemberIdentityEnum.ID_4.getKey());
        changeLegalQuery.setRole(CompanyMemberRoleEnum.ROLE_0.getKey());
        CompanyChangeMemberDO changeLegal = companyChangeMemberService.query(changeLegalQuery);
        if (null != changeLegal) {
            //查询原始法人信息
            CompanyApplyMemberQuery applyLegalQuery = new CompanyApplyMemberQuery();
            BeanUtils.copyProperties(changeLegalQuery, applyLegalQuery);
            //先删除
            applyLegalQuery.setApplyId(companyChangeDO.getApplyId());
            companyApplyMemberService.deleteByItemParam(applyLegalQuery);
            //复制变更数据覆盖原始数据并保存
            CompanyApplyMemberDO applyLegal = new CompanyApplyMemberDO();
            BeanUtils.copyProperties(changeLegal, applyLegal);
            applyLegal.setApplyId(companyChangeDO.getApplyId());
            companyApplyMemberService.save(applyLegal);
        }

        //股东信息
        CompanyChangeMemberQuery holderQuery = new CompanyChangeMemberQuery();
        holderQuery.setChangeId(companyChangeDO.getId());
        holderQuery.setRole(CompanyMemberRoleEnum.ROLE_1.getKey());
        List<CompanyChangeMemberDO> changeHolderList = companyChangeMemberService.queryShareHolderList(holderQuery);
        if (CollectionUtil.isNotEmpty(changeHolderList)) {
            //复制变更数据覆盖原始数据并保存
            //1.先删除法人信息
            CompanyApplyMemberQuery companyApplyMemberQuery = new CompanyApplyMemberQuery();
            companyApplyMemberQuery.setApplyId(companyChangeDO.getApplyId());
            companyApplyMemberQuery.setRole(CompanyMemberRoleEnum.ROLE_1.getKey());
            companyApplyMemberService.deleteByItemParam(companyApplyMemberQuery);
            //2.添加
            for (CompanyChangeMemberDO changeMemberDO : changeHolderList) {
                CompanyApplyMemberDO applyMemberDO = new CompanyApplyMemberDO();
                BeanUtils.copyProperties(changeMemberDO, applyMemberDO);
                companyApplyMemberService.save(applyMemberDO);
            }
        }

        //资料图片
        CompanyChangeImagesQuery changeImagesQuery = new CompanyChangeImagesQuery();
        changeImagesQuery.setChangeId(companyChangeDO.getApplyId());
        List<CompanyChangeImagesDO> changeImagesList = companyChangeImagesService.queryList(changeImagesQuery);
        if (CollectionUtil.isNotEmpty(changeImagesList)) {
            //复制变更数据覆盖原始数据并保存
            //1.先删除资料图片
            companyApplyImagesService.delete(companyChangeDO.getApplyId());
            //2.添加
            for (CompanyChangeImagesDO changeImagesDO : changeImagesList) {
                CompanyApplyImagesDO applyImagesDO = new CompanyApplyImagesDO();
                BeanUtils.copyProperties(changeImagesDO, applyImagesDO);
                applyImagesDO.setApplyId(companyChangeDO.getApplyId());
                companyApplyImagesService.save(applyImagesDO);
            }
        }
    }

    /**
     * 复制 备案数据 ==> 基础信息表
     */
    private void copyRecord2Apply(CompanyChangeDO companyChangeDO) throws ServiceException {
        //员工信息
        CompanyChangeMemberQuery holderQuery = new CompanyChangeMemberQuery();
        holderQuery.setChangeId(companyChangeDO.getId());
        holderQuery.setRole(CompanyMemberRoleEnum.ROLE_0.getKey());
        List<CompanyChangeMemberDO> changeHolderList = companyChangeMemberService.queryShareHolderList(holderQuery);
        if (CollectionUtil.isNotEmpty(changeHolderList)) {
            //1.先删除员工信息
            CompanyApplyMemberQuery companyApplyMemberQuery = new CompanyApplyMemberQuery();
            companyApplyMemberQuery.setApplyId(companyChangeDO.getApplyId());
            companyApplyMemberQuery.setRole(CompanyMemberRoleEnum.ROLE_0.getKey());
            companyApplyMemberService.deleteByItemParam(companyApplyMemberQuery);
            //2.添加
            for (CompanyChangeMemberDO changeMemberDO : changeHolderList) {
                CompanyApplyMemberDO applyMemberDO = new CompanyApplyMemberDO();
                BeanUtils.copyProperties(changeMemberDO, applyMemberDO);
                companyApplyMemberService.save(applyMemberDO);
            }
        }

    }

    @Override
    public List<JSONObject> queryReportList(CompanyChangeQuery query) throws ServiceException {
        return null;
    }
}
